package com.example.practice.fragment;

import java.util.ArrayList;
import java.util.List;

import com.example.practice.R;
import com.example.practice.adapter.ChartAdapter;
import com.example.practice.bean.ChartPagerBean;
import com.example.practice.bean.SensorValue;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;

public class RealTimeChartFragment extends Fragment {
	
	private ViewPager viewPager;
	private ChartAdapter chartAdapter;
	private List<ChartPagerBean> sensorDataBeans = new ArrayList<ChartPagerBean>();
	ChartPagerBean soildHumi = new ChartPagerBean("土壤湿度");
	ChartPagerBean soildTemp = new ChartPagerBean("土壤温度");
	ChartPagerBean airHumi = new ChartPagerBean("空气湿度");
	ChartPagerBean airTemp = new ChartPagerBean("空气温度");
	ChartPagerBean co2 = new ChartPagerBean("CO2");
	ChartPagerBean light = new ChartPagerBean("光照");
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.activity_chart, null);
		viewPager = (ViewPager)view.findViewById(R.id.viewpager);
		chartAdapter = new ChartAdapter(sensorDataBeans);
		addBeans();
		viewPager.setAdapter(chartAdapter);

		return view;
	}
	
	
	private void addBeans(){
		sensorDataBeans.clear();
		sensorDataBeans.add(soildHumi);
		sensorDataBeans.add(soildTemp);
		sensorDataBeans.add(airHumi);
		sensorDataBeans.add(airTemp);
		sensorDataBeans.add(co2);
		sensorDataBeans.add(light);
	}
	

	

	public void onGetSensorValue(SensorValue sensorValue) {
		// TODO Auto-generated method stub
		soildHumi.majorValueList.add(sensorValue.getSoilHumid());
		soildTemp.majorValueList.add(sensorValue.getSoilTemper());
		airTemp.majorValueList.add(sensorValue.getAirTemper());
		airHumi.majorValueList.add(sensorValue.getAirHumid());
		co2.majorValueList.add(sensorValue.getCo2());
		light.majorValueList.add(sensorValue.getLight());
		

		if(soildHumi.majorValueList.size() > 10){
			soildHumi.majorValueList.remove(0);
			soildTemp.majorValueList.remove(0);
			airTemp.majorValueList.remove(0);
			airHumi.majorValueList.remove(0);
			co2.majorValueList.remove(0);
			light.majorValueList.remove(0);
			for(ChartPagerBean chartPagerBean: sensorDataBeans){
				chartPagerBean.times.remove(0);
			}
		}
		
		addBeans();
		
		long time = System.currentTimeMillis();
		for(ChartPagerBean chartPagerBean: sensorDataBeans){
			chartPagerBean.times.add(time);
		}
		
		int current = viewPager.getCurrentItem();
		chartAdapter = new ChartAdapter(sensorDataBeans);
		viewPager.setAdapter(chartAdapter);
		viewPager.setCurrentItem(current);

	}

	
}
